//
//  HSUser.m
//  HSTS
//
//  Created by simon on 2017/2/7.
//  Copyright © 2017年 simon. All rights reserved.
//

#import "HSUser.h"
#define USER                      @"USER"
#define MUSER                     @"MUSER"
#define AUTHTOKEN                 @"AUTHTOKEN"
#define SEARCHHISTORY             @"SEARCHHISTORY"
#define CLOCATION                 @"CLOCATION"


@implementation HSUser
+ (HSUser *)standardUser
{
    NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:USER];
    HSUser *user = nil;
    if (userData != nil) {
        user = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
    }else{
        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:[[HSUser alloc] init]]
                                                  forKey:USER];
    }
    return user;
}

- (void)persist
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:self]
                                              forKey:USER];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)reset
{
    self.searchHistory = nil;
    self.user = nil;
    [self persist];
}

- (void)resetAll
{
    self.searchHistory = nil;
    self.user = nil;
    [self persist];
}

#pragma mark - NSCoding
- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:[self searchHistory] forKey:SEARCHHISTORY];
    [encoder encodeObject:[self user] forKey:MUSER];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if (self) {
        [self setSearchHistory:[decoder decodeObjectForKey:SEARCHHISTORY]];
        [self setUser:[decoder decodeObjectForKey:MUSER]];
    }
    return self;
}
@end
